<?php
namespace App\Http\Controllers\Wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\RedisService;
use App\Services\Wechat;
use App\Models\Article;
use App\Models\Parter;
use App\Models\Suggest;
use App\Models\Wxuser;
use App\Models\Booking;
use App\Models\User;
use App\Http\Requests\ApiRequest;
use EasyWeChat;
use Log;

class IndexController extends Controller
{
    

    // 返回openid    
    public function getOpenid(Request $request)
    {
        $rs['status'] = false;
        $code = trim($request->code);
        $mini = EasyWeChat::miniProgram(); // 小程序
        $result = $mini->auth->session($code); // $code 为wx.login里的code
        if(!array_key_exists('openid', $result)) {
            $rs['msg'] = $result['errmsg'];
            return response()->json($rs);
        }
        $rs['status'] = true;
        $rs['openid']      = $result['openid'];
        $rs['session_key'] = $result['session_key'];
        return response()->json($rs);
    }

    /**
     * 获取微信用户信息，主要是unionid
     */
    public function getWxUser(Request $request)
    {
        $rs['status'] = false;      
        $session     = $request->session_key;
        $iv          = $request->iv;
        $encryptData = $request->encryptData;
        $app         = EasyWeChat::miniProgram(); // 小程序
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptData);
        if($decryptedData) {
            $rs['status'] = true;
            $rs['data'] = $decryptedData;            
            return response()->json($rs);
        }
        return response()->json($rs);
    }
   
    // 小程序验证身份获取token
    public function getToken(Request $request)
    {
        $rs['status'] = true;
        $data = array_only($request->all(),['avatar','nickname','unionid','small_openid']);
        $data['token']       = str_random(16);
        $data['headimgurl']  = array_pull($data,'avatar');       
        $map['small_openid'] = $data['small_openid'];
        $user = Wxuser::updateOrCreate($map,$data);

        $rs['data']['token'] =  $data['token'];
       
        return response()->json($rs);   
    }

    
   

   

    public function upload(Request $request)
    {
        $rs['status'] = true;
        $folder       = 'public/'.date('Ymd');
        
        if ($request->isMethod('post')) {
            $file = $request->file('file');                        
                

            $path = '/'.$file->store('public/'.date('Ymd'));  
            $rs['data'] = str_replace('public', 'storage', $path);   
       
               
            return response()->json($rs);
            

        }
        return response()->json(['rs' => false, 'msg' => '不是正确请求方式']);
    }

    /**
     * 常见问题
     */
    public function articleList(Request $request)
    {
        $rs['status'] = true; 
        $cate_id      = $request->cate_id?$request->cate_id:1;      
        $data = Article::where('cate_id',$cate_id )->orderBy('weight','asc')->get();
        $rs['data'] = $data;
        return response()->json($rs);
    }

    /**
     * 关于我们
     */
    public function about(Request $request)
    {
        $rs['status'] = true;       
        $data = Article::where('cate_id',100)->first();
        $rs['data'] = $data;
        return response()->json($rs);
    }

    /**
     * 联系我们
     */
    public function contact(Request $request)
    {
        $rs['status'] = true;       
        $data = Article::where('cate_id',101)->first();
        $rs['data'] = $data;
        return response()->json($rs);
    }

   

    /**
     * 合作伙伴
     */
    public function parter(Request $request)
    {
        $rs['status'] = true;       
        $list = Parter::get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    

    public function getSmallcode(Request $request)
    {   // scene_value = '20-2';  商品id,用户id ; id, agent_id
        $value = explode('-', $request->scene_value);

        $app = EasyWeChat::miniProgram(); // 小程序
        //$page = 'pages/productDetails/productDetails?id='.$value[0].'&agent_id='.$value[1];
        $page = 'pages/productDetails/productDetails';
         
        $response = $app->app_code->getUnlimit($request->scene_value, [
            'page'  => $page,
            'width' => 300,
            
        ]);
      
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save('uploads/smallcode', $request->scene_value.'.png');
            $rs['status'] = true;
            $rs['data'] = '/uploads/smallcode/'.$filename;
            return response()->json($rs);
        }
    }

    public function suggest(ApiRequest $request)
    {
        $data = $request->pure();
        Suggest::create($data);
        $rs['status'] = true;
        $rs['msg']    = '提交成功';
        return response()->json($rs);
    }

    public function booking(ApiRequest $request)
    {
        $data = $request->pure();
        $flag = Booking::create($data);
        if($flag) {
            $users = User::all();
            $msg = $flag->toArray();
            foreach ($users as $k => $v) {
                if(empty($v->openid)) continue;
                $msg['openid'] = $v->openid;
                $msg['url'] = config('app.url').'/user/booking-show/'.$flag->id;
                Wechat::sendMsgTpl('booking',$msg);
            }
           
            
        }   
        $rs['status'] = true;
        $rs['msg']    = '提交成功';
        return response()->json($rs);
    }


    public function getBooking(ApiRequest $request)
    {
        $where['wxuser_id'] = $request->wxuser_id;
        $list         = Booking::where($where)->orderBy('id','desc')->paginate(10);
        $rs['data']   = $list;
        $rs['status'] = true;
        $rs['msg']    = '提交成功';
        return response()->json($rs);
    }
   


    
}
